import router from '@/router'
import store from '@/store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 白名单代表没有token也可以访问的页面
const whiteList = ['/login', '/404']
// to表示要到哪里去
// from表示从哪里过来
// next表示放行(next()) 或者重定向(next({path:'/'}))
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    // 有token的情况
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const userInfo = store.state.user.UserInfo
      if (Object.keys(userInfo).length <= 0) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    // 没有token的情况
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  }
})
// 全局后置守卫
router.afterEach((to, from) => {
  NProgress.done()
})
